package a.b.c;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.receiver.UsbBootReceiver;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;

import a.b.c.utils.USBUtils3;

public class MainActivity extends AppCompatActivity {

    private EditText mEtWrite;
    private TextView mTvRead;
    private File uFile;

    public static final String TAG = "RWUSB";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEtWrite = findViewById(R.id.et_write);
        mEtWrite.setText("hello " + System.currentTimeMillis());
        mTvRead = findViewById(R.id.tv_read);
        setTitle("读写U盘demo");

        uFile = new File(USBUtils3.getInstance().searchPath(), "test.txt");
        Log.i(TAG, "读写文件：" + uFile.getAbsolutePath());

        UsbBootReceiver usbBootReceiver = UsbBootReceiver.getInstance();
        usbBootReceiver.registerReceiver(this);
        usbBootReceiver.setOnChangeListener(new UsbBootReceiver.SetVolumeListen() {
            @Override
            public void UVolume(int position, String path) {
                if (position == 2 && new File(path).exists()) {
                    uFile = new File(path, "test.txt");
                    Log.i(TAG, "通过UsbBoot.jar获取到U盘路径");
                }
            }

            @Override
            public void UVloumeList(List<Integer> list) {

            }
        });
    }

    public void read(View v) {
        if (!hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            requestPermissions(Manifest.permission.READ_EXTERNAL_STORAGE);
            return;
        }

        new Thread() {
            @Override
            public void run() {
                super.run();
                String result = USBUtils3.getInstance().read(uFile);
                mTvRead.post(() -> mTvRead.setText("读取结果：" + result));
            }
        }.start();

    }

    public void write(View v) {
        if (!hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            requestPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return;
        }

        new Thread() {
            @Override
            public void run() {
                super.run();
                String data = mEtWrite.getText().toString();
                String err = USBUtils3.getInstance().write(data.getBytes(StandardCharsets.UTF_8), uFile);
                mEtWrite.post(() -> Toast.makeText(MainActivity.this, TextUtils.isEmpty(err) ? "写成功" : "写失败: " + err, Toast.LENGTH_SHORT).show());
            }
        }.start();
    }

    private boolean hasPermission(String permission) {
        return ContextCompat.checkSelfPermission(this, permission) ==
                PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermissions(String... permission) {
        ActivityCompat.requestPermissions(this, permission, 10);
        //requestPermissions(permission, 10);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "onRequestPermissionsResult: requestCode=" + requestCode + ", permissions=" + getString(permissions) + ", grantResults=" + getString(grantResults));
    }

    public String getString(String[] arr) {
        StringBuilder sb = new StringBuilder();
        for (String o : arr) {
            sb.append(o);
            sb.append(", ");
        }
        return sb.toString();
    }

    public String getString(int[] arr) {
        StringBuilder sb = new StringBuilder();
        for (int o : arr) {
            sb.append(o);
            sb.append(", ");
        }
        return sb.toString();
    }
}